<?php

	// +----------------------------------------------------------------------
	// | 推荐位模型
	// +----------------------------------------------------------------------
	// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
	// +----------------------------------------------------------------------
	// | Author: 微尘 <yicmf@qq.com>
	// +----------------------------------------------------------------------

	namespace app\model\cms;

	use think\Log;

	class Position extends Common
	{

		/**
		 * 推荐位信息
		 */
		public static function getPosition()
		{
			return self::where('status', 1)->column('id,title');
		}

		/**
		 * 推荐位数据移除.
		 * @param unknown $id
		 */
		public function positionDataRemove($id)
		{
			if (empty($id)) {
				$this->error = '数据异常';

				return false;
			}
			$data = $this->positiondata()
				->where('id', $id)
				->find();
			if (!$data) {
				return false;
			}
			$position_id = $data->position_id;
			$data->status = -2;

			return $data->save();
		}

		/**
		 * 批量添加推荐位.
		 * @param array $ids 推荐位ID集合
		 * @param object $document 插入模型对象
		 * @param boolean $is_update 是否是更新模式
		 * @return bool|unknown
		 */
		public function addDataAll($ids, $document, $is_update = false)
		{
			if ($is_update) {
				//先删除所有
				PositionData::destroy(['document_id' => $document['id']]);
			}
			// 查询存在推荐位
			if ($ids && count($ids) > 0) {
				//增加推荐数据;
				$has_ids = $this->where('id', 'in', $ids)->column('id');
				if (!$has_ids || count($has_ids) !== count($ids)) {
					// 数据异常;
					Log::write('推荐位数据异常：' . var_export($document, true));
				}
				if ($has_ids && count($has_ids) > 0) {
					$data_all = [];
					foreach ($has_ids as $value) {
						$insertData = [];
						$insertData['document_id'] = $document['id'];
						$insertData['title'] = $document['title'];
						$insertData['description'] = $document['description'];
						$insertData['category_id'] = $document['category_id'];
						$insertData['pattern_id'] = $document['pattern_id'];
						$insertData['cover_id'] = $document['cover_id'];
						$insertData['sort'] = 0;
						$insertData['only_url'] = 0;
						$insertData['position_id'] = $value;
						$insertData['expiration'] = '';
						$data_all[] = $insertData;
					};
					// 批量添加
					$positionDataModel = new PositionData();
					$result = $positionDataModel->saveAll($data_all);
				}
			}
			return true;
		}

		/**
		 * 推荐位关联.
		 */
		public function positiondata()
		{
			return $this->hasMany('PositionData');
		}
		/**
		 * 写入修改
		 * @param $data
		 */
		public static function onBeforeInsert($data)
		{
			$data['status'] = 1;
		}


	}
